package cn.huijielong.modules.oss.cloud;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import cn.huijielong.common.exception.VSException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 * @date 2017-11-25 15:41
 */
public class QiniuCloudStorageService extends CloudStorageService {
	private Logger logger = LoggerFactory.getLogger(QiniuCloudStorageService.class);
    private UploadManager uploadManager;
    private String token;
    private final static long expires=60*60*12; //有效时长，单位秒。默认3600s


    public QiniuCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
                uploadToken(config.getQiniuBucketName());
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            
        } catch (Exception e) {
            throw new VSException("上传文件失败，请核对七牛配置信息", e);
        }
        
        if(path.startsWith("/") && config.getQiniuDomain().endsWith("/")) {
        	path=path.substring(1);
        }else if(!path.startsWith("/") && !config.getQiniuDomain().endsWith("/")) {
        	path="/"+path;
        }
        return config.getQiniuDomain() + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new VSException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQiniuPrefix(), suffix));
    }
    @Override
    public boolean delete(String path) {
    	return delete(path, config.getQiniuBucketName());
    }
    @Override	
    public boolean delete(String path,String bucket) {
		try {
			if(path.startsWith(config.getQiniuDomain())) {
				path=path.substring(config.getQiniuDomain().length());
			}
			Auth auth=Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey());
			//实例化一个BucketManager对象
	        BucketManager bucketManager = new BucketManager(auth, new Configuration(Zone.autoZone()));
	        Response resp=bucketManager.delete(bucket, path);
			if (!resp.isOK()) {
				throw new RuntimeException(resp.toString());
			}
		} catch (Exception e) {
			logger.error("七牛删除文件出错", e);
			throw new VSException("七牛删除文件出错：" ,e);
		}
		return true;
	}

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
    }
    @Override
    public String getPrefix(){
        return config.getQiniuPrefix();
    }
    public String getToken() {
        return token;
    }

	@Override
	public String uploadSuffix(String bucketName, byte[] data, String path) {
		String upToken = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
                uploadToken(bucketName);
		try {
            Response res = uploadManager.put(data, path, upToken);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            
        } catch (Exception e) {
            throw new VSException("上传文件失败，请核对七牛配置信息", e);
        }

        return config.getQiniuDomain() + "/" + path;
	}

	@Override
	public String getPrivateUrl(String targetUrl) {
		Auth auth=Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey());
		return auth.privateDownloadUrl(targetUrl,expires);
	}
}
